package nick.xbmc.library
{
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.SharedObject;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.utils.Base64Decoder;
	
	import nick.xbmc.utils.Hash;
	
	public class MovieFactoryRedux extends EventDispatcher
	{
		private static const COMPLETE:String = "COMPLETE";
		
		private var bl:BulkLoader;
		
		private var prefix:String = "http://";
		//private var server:String = "nickharbin/";
		private var server:String = "192.168.2.4/";
		//private var server:String = "mce/";
		//private var server:String = "localhost/";
		private var middle:String = "xbmcCmds/xbmcHttp?command=";
		private var queryVid:String = "queryvideodatabase(";
		private var query:Array = new Array();
		private var postfix:String = ")";
		
		public var movies:Array = new Array();
		
		private var sharedMovies:SharedObject;
		
		private var loadFromSharedObject:Boolean = false;
		
		public function MovieFactoryRedux()
		{				
			bl = new BulkLoader("image-loader");
			
			sharedMovies = SharedObject.getLocal("mymovies");
	
			initQueryArray();
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, buildMovieArray)
			loader.load(new URLRequest(prefix + server + middle + queryVid + "select " + query["MovieThumbnailURLS"] +","+
									   													query["MovieID"] +","+
									   													query["MovieTitle"] +","+
									   													query["MoviePlot"] +","+
									   													query["MoviePlotOutline"] +","+
									   													query["MovieTagline"] + "," +
									   													query["MovingRatingVotes"] + "," +
									   													query["MovieRating"] + "," +
									   													query["MovieWriters"] + "," +
									   													query["MovieYearReleased"] + "," +
																						query["MovieIMDBID"] + "," +
																						query["MovieRuntime"] + "," +
																						query["MovieMPAARating"] + "," +
																						query["MovieGenre"] + "," +
																						query["MovieDirector"] + "," +
																						query["MovieStudio"] + "," +
																						query["MovieIDFile"] + "," +
																						query["FolderPath"] + "," +
																						query["Filename"] + "," +
																						query["PathID"] + "," +
																						query["FileID"] + "," +
																						query["MovieFanartURLS"] + 	
									   												" from movie inner join files on " + 
									   													query["MovieIDFile"] + "=" + query["FileID"] +
									   												" inner join path on " +
									   													query["FilePathID"] + "=" + query["PathID"] +
									   												postfix));			
		}
		
		private function initQueryArray():void
		{
			query["MovieID"] = "movie.idMovie";
			query["MovieTitle"] = "movie.c00";
			query["MoviePlot"] = "movie.c01";
			query["MoviePlotOutline"] = "movie.c02";
			query["MovieTagline"] = "movie.c03";
			query["MovingRatingVotes"] = "movie.c04";
			query["MovieRating"] = "movie.c05";
			query["MovieWriters"] = "movie.c06";
			query["MovieYearReleased"] = "movie.c07";
			query["MovieThumbnailURLS"] = "movie.c08";
			query["MovieIMDBID"] = "movie.c09";
			query["c10"] = "movie.c10";
			query["MovieRuntime"] = "movie.c11";
			query["MovieMPAARating"] = "movie.c12";
			query["c13"] = "movie.c13";
			query["MovieGenre"] = "movie.c14";
			query["MovieDirector"] = "movie.c15";
			query["c16"] = "movie.c16";
			query["c17"] = "movie.c17";
			query["MovieStudio"] = "movie.c18";
			query["c19"] = "movie.c19";
			query["MovieFanartURLS"] = "movie.c20";
			query["MovieIDFile"] = "movie.idFile";
			query["FolderPath"] = "path.strPath";
			query["Filename"] = "files.strFilename";
			query["PathID"] = "path.idPath";
			query["FileID"] = "files.idFile";
			query["FilePathID"] = "files.idPath";			
		}
		
		private function xmlListToArray(xmlList:XMLList, urlPrefix:String=null):Array
		{
			var returnArray:Array = new Array(xmlList.length());
			
			if (urlPrefix != null)
			{
				for (var i:Number = 0; i < returnArray.length; i++)
				{
					returnArray[i] = urlPrefix + xmlList[i];
				}
			}
			else
			{
				for (var x:Number = 0; x < returnArray.length; x++)
				{
					returnArray[x] = xmlList[x];
				}
			}
			
			return returnArray;
		}
		
		private function buildMovieArray(event:Event):void
		{
			var movieXML:XML = new XML(event.target.data);
			
			for (var i:Number = 0; i < movieXML.field.length(); i++)
			{				
				if (movieXML.field[i].thumb.length() != 0)
				{
					var movie:Movie = new Movie();
										
					movie.ThumbnailURLS = xmlListToArray(movieXML.field[i].thumb);
					movie.MovieID = movieXML.field[i + 1];
					movie.Title = movieXML.field[i + 2];
					movie.Plot = movieXML.field[i + 3];
					movie.PlotOutline = movieXML.field[i + 4];
					movie.Tagline = movieXML.field[i + 5];
					movie.RatingVotes  = movieXML.field[1 + 6];
					movie.Rating = movieXML.field[i + 7];
					movie.Writers = movieXML.field[i + 8];
					movie.YearReleased = movieXML.field[i + 9];
					movie.IMDBID = movieXML.field[i + 10];
					movie.Runtime = movieXML.field[i + 11];
					movie.MPAARating = movieXML.field[i + 12];
					movie.Genre = movieXML.field[i + 13];
					movie.Director = movieXML.field[i + 14];
					movie.Studio = movieXML.field[i + 15];
					movie.IDFile = movieXML.field[i + 16];
					movie.Path = movieXML.field[i + 17];
					movie.File = movieXML.field[i + 18];
				}
				
				if (movieXML.field[i].fanart.length() != 0)
				{
					var url:String = movieXML.field[i].fanart.attribute("url");
					movie.FanartURLS = xmlListToArray(movieXML.field[i].fanart.thumb, movieXML.field[i].fanart.attribute("url"));
															
					var hash:String = Hash.getFileName(movie.Path + movie.File);
					
					movie.FanartInUse = "special://masterprofile/Thumbnails/Video/Fanart/" + hash + ".tbn";
					movie.ThumbInUse = "special://masterprofile/Thumbnails/Video/" + hash.charAt(0) + "/" + hash + ".tbn";
					
					bl.addEventListener(BulkProgressEvent.COMPLETE, moviesBuiltHandler);
					
					bl.add(prefix + server + middle + "FileDownload(" + movie.ThumbInUse + ")", {id:"T" + movie.MovieID})
					bl.add(prefix + server + middle + "FileDownload(" + movie.FanartInUse + ")", {id:"F" + movie.MovieID});			
					
					movies.push(movie);
				}
			}
			
			movies.sortOn("Title");
			
			bl.start();
		}
		
		private function moviesBuiltHandler(e:BulkProgressEvent):void
		{
			var baseT:Base64Decoder = new Base64Decoder();
			var baseF:Base64Decoder = new Base64Decoder();	
			
			var thumbEncoded:String;
			var fanartEncoded:String;
					
			//baseT.decode(encoded);
			//baseF.decode(encoded);
			
			for each (var m:Movie in movies)
			{
				 for (var i:Number = 0; i < e.target.items.length; i++)
				 {
				 	if ("T" + m.MovieID == e.target.items[i].id)
				 	{
				 		thumbEncoded = e.target.items[i].content;
				 		thumbEncoded = thumbEncoded.replace("<html>", "");
				 		thumbEncoded = thumbEncoded.replace("</html>", "");
				 		
				 		baseT.decode(thumbEncoded);
				 		
				 		m.ThumbBytes = baseT.toByteArray();
				 	}
				 	
				 	if ("F" + m.MovieID == e.target.items[i].id)
				 	{
				 		fanartEncoded = e.target.items[i].content;
				 		fanartEncoded = fanartEncoded.replace("<html>", "");
				 		fanartEncoded = fanartEncoded.replace("</html>", "");
				 		
				 		baseF.decode(fanartEncoded);
				 		
				 		m.FanartBytes = baseF.toByteArray();
				 	}
				 }
			}
			
			sharedMovies.data.movies = movies;
			sharedMovies.flush(100000);
		}
	}
}